package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.entity.SysMessage;
import com.blog.entity.SysUser;
import com.blog.service.SysMessageService;

import com.blog.util.dto.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cgx
 * @Date 2022/3/25 22:59
 */
@Controller
@RequestMapping("/message")
public class SysMessageController {

    @Resource
    SysMessageService messageService;

    @GetMapping("test")
    @ResponseBody
    public Map<String,Object> test(){
        List<SysMessage> list = messageService.list();


        Map<String,Object> map = new HashMap<>();
        map.put("data",list);
        map.put("code","200");
        map.put("message","操作成功");
        return map;
    }

    @PostMapping("readMyMessage")
    @ResponseBody
    public AjaxResult readMyMessage(){
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser)subject.getPrincipal();

        QueryWrapper<SysMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",sysUser.getId()).eq("read_state",0);
        List<SysMessage> list = messageService.list(queryWrapper);
        //该用户存在未读消息
        List<SysMessage> updateList = new ArrayList<>();
        if (list.size() > 0){
            for (int i = 0; i < list.size(); i++) {
                SysMessage sysMessage = list.get(i);
                sysMessage.setReadState(1);
                updateList.add(sysMessage);
            }
        }
        boolean b = messageService.updateBatchById(updateList);
        return AjaxResult.success();
    }
}
